package echo;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-04-10
 * Time: 21:27
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String ip;
    private int port;
    public UdpEchoClient(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        this.ip = ip;
        this.port = port;
    }
    public void start() throws IOException {
        System.out.println("客户端连接");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.println("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(ip),port);
            socket.send(requestPacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength(),"UTF-8");
            System.out.println("request"+request+"response"+response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
